import React, {Component} from "react";
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import {Button, FooterContainer, HomeWrapper, MaxContainer, PageContainer, PageTitleContainer} from './style';
import {VCode2, VCodeContainer4Page, VCodeInput2} from "@/style/VCode";
import BuildVCode, {SaveInputVCode} from "@/util/BuildVCode";
import _ from 'lodash';
import {editorUpload, errorMsg, load, queryState, successMsg} from "@/util/global";
import {Action2SavePage} from "./store/action";
import {connect} from "react-redux";
import {saveNewPage} from "@/util/Api";
import {Col, Row, Select, Transfer} from 'antd';
import {Refresh} from "@/store/common/category/pageCategory/action";
import {commonRemoveFile} from "@/util/FileUtil";
import ImageUpload from "@/common/Upload/ImageUpload";
import {getSimpleGameInfoList} from "@/api/JustGameInfo";

const {Option} = Select;

/**
 * 上传文章
 * @param props
 * @constructor
 */
class UploadPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            editorState: BraftEditor.createEditorState(null),
            pageTitle: '',
            pageCategory: '',
            fileItems: [],
            gameList: [],
            selectGames: [],
            searchGameKeyword: '',
            size: 10,
            page: 1,
            total: 0,
        }
        this.save = this.save.bind(this);
        this.handleEditorChange = this.handleEditorChange.bind(this);
        this.handleTitleChange = this.handleTitleChange.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.props.handleInitPageCategory();
        this.handleDelImage = this.handleDelImage.bind(this);
        this.filterOption = this.filterOption.bind(this);
        this.handleSelectGames = this.handleSelectGames.bind(this);
        this.handleSearch = this.handleSearch.bind(this);
        this.loadGameList = this.loadGameList.bind(this);
    }

    componentDidMount() {
        // 生成验证码
        BuildVCode('feature-page-vcode');
        this.loadGameList();
    }

    loadGameList() {
        let params = {
            size: this.state.size,
            page: this.state.page,
            keyword: this.state.searchGameKeyword,
        }
        getSimpleGameInfoList(params).then(res => {
            if (res.success) {
                this.setState({
                    gameList: res.data.rows,
                    total: res.data.total,
                    page: res.data.page,
                    size: res.data.size,
                })
            }
        })
    }

    async handleEditorChange(editorState) {
        this.setState({editorState})
    }

    async handleTitleChange(e) {
        this.setState({pageTitle: e.target.value})
    }

    handleChange(e) {
        this.setState({pageCategory: e})
    }

    handleDelImage(e) {
        commonRemoveFile(this, this.state.fileItems[0]).then();
        e.stopPropagation()
    }

    handlePaginationChange(page, size) {
        /* 分页器事件 */
        this.setState({page, size}, this.loadGameList)
    }

    handleSelectGames = selectGames => {
        console.log(selectGames)
        this.setState({selectGames});
    };


    handleSearch = (dir, value) => {
        console.log('search:', dir, value);
    };

    async save() {
        if (_.isEmpty(queryState('window.VerificationCode'))) {
            return errorMsg('请输入验证码！');
        } else if (_.isEmpty(this.state.pageTitle)) {
            return errorMsg('请输入文章标题！');
        } else if (_.isEmpty(this.state.pageCategory)) {
            return errorMsg('请选择文章分类！');
        } else if (this.state.fileItems.length === 0) {
            return errorMsg('请上传封面');
        }
        load(true)
        saveNewPage({
            pageTitle: this.state.pageTitle,
            pageContent: this.state.editorState.toRAW(),
            pageCategory: this.state.pageCategory,
            gameIds: this.state.selectGames,
            photoUrl: this.state.fileItems[0].imgUrl
        }).then(
            res => {
                if (res.success === true) {
                    successMsg('上传文章成功')
                    this.props.history.push('/home')
                }
            }
        )
        load(false)
    }

    handleUploadImg() {

    }

    filterOption = (inputValue, option) => option.description.indexOf(inputValue) > -1;

    render() {

        const controls = [
            {
                key: 'bold',
                text: <b>加粗</b>
            },
            'italic', 'underline', 'separator', 'link', 'separator', 'media'
        ]
        return (
            <HomeWrapper>
                <MaxContainer>
                    <PageContainer>
                        <Row gutter={[16, 16]}>
                            <Col span={6}>
                                <div style={{width: '100%', height: '200px'}}>
                                    <ImageUpload width={200}
                                                 height={200}
                                                 that={this}
                                                 placeholder={"点击上传封面"}
                                                 shouldKnow={"请勿上传大于3Mb文件"}
                                                 fileList={this.state.fileItems}
                                                 onDelete={this.handleDelImage}/>
                                </div>
                            </Col>
                            <Col span={18}>
                                <Row gutter={[8, 8]}>
                                    <Col span={24}>
                                        <label>文章类型：</label>
                                        <Select size={"small"} style={{width: 200}}
                                                placeholder={"请选择文章类别"} onChange={(e) => this.handleChange(e)}>
                                            {

                                                this.props.pCategoryList.rows ?
                                                    this.props.pCategoryList.rows.map(item => {
                                                        return <Option value={item.id}
                                                                       key={item.id}>{item.name}</Option>
                                                    }) : null
                                            }
                                        </Select>
                                    </Col>
                                    <Col span={24}>
                                        <label style={{float: "left"}}>关联游戏：</label>
                                        <Transfer
                                            style={{float: "left"}}
                                            dataSource={this.state.gameList}
                                            showSearch
                                            rowKey={item => item.id}
                                            filterOption={this.filterOption}
                                            targetKeys={this.state.selectGames}
                                            onChange={this.handleSelectGames}
                                            onSearch={this.handleSearch}
                                            render={item => item.name}
                                            pagination={{
                                                defaultCurrent: 1,
                                                defaultPageSize: 10,
                                                pageSize: this.state.size,
                                                current: this.state.page,
                                                total: this.state.total,
                                                onChange: this.handlePaginationChange,
                                                size: "small"
                                            }}
                                        />
                                    </Col>
                                </Row>
                            </Col>
                            <Col span={24}>
                                <PageTitleContainer
                                    value={this.state.pageTitle}
                                    onChange={this.handleTitleChange}
                                    style={{textAlign: 'center', fontWeight: '600', fontSize: '25px'}}
                                    placeholder={'请输入文章标题！（5-30个字符）'}
                                    maxLength={60}
                                    size={'large'}
                                    bordered/>
                            </Col>
                            <Col span={24}>
                                <BraftEditor
                                    controls={controls}
                                    style={{border: '1px solid #888'}}
                                    value={this.state.editorState}
                                    onChange={this.handleEditorChange}
                                    media={{uploadFn: editorUpload}}
                                />
                            </Col>
                            <Col span={24}>
                                <FooterContainer>
                                    <Button className={'writing'} onClick={() => this.save()}>发布</Button>
                                    <VCodeContainer4Page style={{marginTop: '9px'}}>
                                        <VCodeInput2
                                            value={this.props.VerificationCode}
                                            onChange={(e) => SaveInputVCode(e.target.value)}/>
                                        <VCode2 id={'feature-page-vcode'}
                                                onClick={() => BuildVCode('feature-page-vcode')}
                                        />
                                    </VCodeContainer4Page>
                                </FooterContainer>
                            </Col>
                        </Row>
                    </PageContainer>
                </MaxContainer>
            </HomeWrapper>
        )
    }
}

const mapStateToProps = (state) => {
    return {
        VerificationCode: state.getIn(['window', 'VerificationCode']),
        pCategoryList: state.getIn(['pageCategory']).toJS()['pageCategoryList']
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        handleSavePageData(value) {
            dispatch(Action2SavePage(value));
        },
        handleInitPageCategory() {
            dispatch(Refresh())
        }
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(UploadPage);
